package gov.army.workshop.baseworkshop.service.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


import gov.army.workshop.baseworkshop.model.ExampleObject;
import gov.army.workshop.baseworkshop.model.ExampleObjects;
import gov.army.workshop.baseworkshop.service.ExampleService;

public class ExampleServiceImpl extends HibernateDaoSupport implements ExampleService {
	
	
	public ExampleObjects query(String text) {
		DetachedCriteria c = DetachedCriteria.forClass(ExampleObject.class);
		c.add(Restrictions.like("text", text,MatchMode.ANYWHERE).ignoreCase());
		
		@SuppressWarnings("unchecked")
		List<ExampleObject> objs = this.getHibernateTemplate().findByCriteria(c);
		ExampleObjects exampleObjects = new ExampleObjects();
		exampleObjects.addAll(objs);
		return exampleObjects;
		
	}
	
	public ExampleObject findByKey(Long key) {
		return (ExampleObject) getHibernateTemplate().get(ExampleObject.class	,key);
	}

	@SuppressWarnings("unchecked")
	public ExampleObjects findByPath() {
		ExampleObjects exampleObjects = new ExampleObjects();
		exampleObjects.addAll(this.getHibernateTemplate().loadAll(ExampleObject.class));
		
		if (exampleObjects.getExampleObjects().size() == 0) {
			for (int i=0;i < 50;i++) {
				ExampleObject exampleObject = new ExampleObject();
				exampleObject.setText("Object # " + i);
				getHibernateTemplate().save(exampleObject);
			}
			exampleObjects.addAll(this.getHibernateTemplate().loadAll(ExampleObject.class));
		}
		
		
		return exampleObjects;
	}

}
